//付款管理
interface IFeeSettlePayManageViewModel extends IBaseViewModel<IFeeSettlePayManageQueryTerms>{
    /**
     * ui-grid
     */
    gridOptions:uiGrid.IGridOptionsOf<FeeSettleBillListItemResponse>;
    /**
     * 选中费用列表
     */
    selectedFeePayListInfo:selectFeePayList[];
    /**
     * 全选
     */
    selectAllEvent():void;
    /**
     * 退回
     */
    backEvent():void;
    /**
     * 付款
     */
    payEvent(id:string):void;
    /**
     * 导出
     */
    exportEvent():void;
    /**
     * 开户银行disable
     */
    openBankDis:boolean;

    /**
     * 银行卡卡号
     */
    bankCode:string;
    /**
     * 开户银行
     */
    bankName:string;
    /**
     * 持卡人
     */
    holder:string;
    /**
     * 获取银行卡名称
     */
    getBankName():void;
    /**
     * 重试按钮
     */
    retryEvent(feeStatusStr:string,id:string):void;
    /**
     * 重试付款保存
     */
    paySave(id:string):void;
    /**
     * 结算单付款
     */
    settlePay():void;
    /**
     * 全选
     */
    selectedAll():void;
    /**
     * 结算人员下拉
     */
    reckonerIdListDropDown:EmployeeListItemResponse[];
    /**
     * 付款方式下拉
     */
    paymentMethodDropDown:ValueListItemResponse[];
    /**
     * 费用状态下拉
     */
    feeStatusListDropDown:ValueListItemResponse[];

    /**
     * 清空已选
     */
    clearSelectAll():void;
    /**
     * 查看详情
     */
    settleDetailBtn(id:string):void;

    /**
     * 付款权限btn  
     */
    canSettlePayBtn:boolean;
    /**
     * 付款人退回权限btn
     */
    canSettleReturnBtn:boolean;
    /**
     * 删除选中
     */
    deleteSelectedPayData(id:string):void;

    searchType(id:string):void;
    /**
     * 列表高度
     */
    heightA:number
}

interface selectFeePayList{
    /**
     * 费用id
     */
    id:string;
    /**
     * 费用状态
     */
    feeStatus:string;
    /**
     * 应付总编号
     */
    billCode:string;
}

/**
 * 查询条件
 */
interface IFeeSettlePayManageQueryTerms{
    /**
     * 应付总编号
     */
    feeSettleBillCode:string;
    /**
     * 承运商名称
     */
    carrierName:string;
    /**
     * 付款方式
     */
    paymentMethod:string;
    /**
     * 合同号
     */
    contractNumber:string;
    /**
     * 结算起始时间
     */
    startTime:string;
    /**
     * 结算结束时间
     */
    endTime:string;
    /**
     * 结算人员
     */
    reckonerId:string;
    /**
     * 费用状态
     */
    feeStatus:string;
    //11.1新增
    /**
     * 费用金额
     */
    feeTotal:string;
}

class feeSettlePayManageController extends ListController<IFeeSettlePayManageViewModel,IFeeSettlePayManageQueryTerms>{
    gridApi: uiGrid.IGridApiOf<FeeSettleBillListItemResponse>;
    /**
     * 选定选中，防止在翻页恢复选中效果时候误操作
     */
    lockSelect: boolean = false;
    orderBy: number = 0;
    asc: boolean = true;
    payBtn:boolean = true;

    feeStatusList:string = "6,7,8,9,10,11";

    constructor($scope:IFeeSettlePayManageViewModel,private feeService:IFeeService,private $ngBootbox:BootboxService,private $state:ng.ui.IStateService,private routeService:routeService,private valueService:IValueService,private $loading:any,private bankService:IBankService,private $interval: ng.IIntervalService,private employeeService:IEmployeeService,private authorizationService:IAuthorizationService,private $timeout:ng.ITimeoutService,private $location:ng.ILocationService,private exportService:IexportService,private commonService:ICommonService){
        super($scope);
        this.init();
    }

    init():void{
        super.init();
        this.$scope.selectedFeePayListInfo = [];
        this.$scope.openBankDis = true;
        this.$scope.queryTerms={
            feeSettleBillCode:"",
            carrierName:"",
            paymentMethod:"",
            contractNumber:"",
            startTime:"",
            endTime:"",
            reckonerId:"",
            feeStatus:"",
            feeTotal:""
        };
        this.$scope.gridOptions = {
			enableSelectAll: false,//全选禁用
			enableFullRowSelection: true,
			paginationPageSizes: [10, 20, 30],
			useExternalPagination: true,
			useExternalSorting: true,
			enableColumnResizing: true,
            multiSelect:true,
			columnDefs: [
                            { displayName: '应付总编号', field: 'billCode', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '12%' },
							{ displayName: '结算承运商', field: 'carrier', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, },
							{ displayName: '费用数量', field: 'feeCount', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '8%' },
							{ displayName: '付款方式', field: 'paymentMethod', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '8%' },
							{ displayName: '费用金额', field: 'totalMoney', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '8%' },
							{ displayName: '费用状态', field: 'feeStatus', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '8%' },
							{ displayName: '持卡人姓名', field: 'holder', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '8%' },
                            { displayName: '结算人员', field: 'reckonerName', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, },
							{ displayName: '结算时间', field: 'settleTime', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, },
							{ displayName: '付款时间', field: 'payTime', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, },
                            {
                                name: "操作",
                                cellFilter: 'checkmark',
                                cellTemplate: '<div>'
                                                + '<a class="fa fa-eye m-l-xs  primary text-info" title="查看详情" ng-click="grid.appScope.settleDetailBtn(row.entity.id)" ></a>'
                                                 + '<a ng-if="row.entity.feeCanPaidType ==\'2\' " class="fa fa-jpy m-l-xs  primary text-info" title="在线支付" ng-click="grid.appScope.payEvent(row.entity.id)" ></a>'
                                                 + '<a ng-if="row.entity.paymentMethod ==\'打卡\' && row.entity.feeStatus ==\'付款中\'" class="glyphicon glyphicon-search m-l-xs  primary text-info" title="查询状态" ng-click="grid.appScope.searchType(row.entity.id)" ></a>'
                                                 + '<a ng-if="row.entity.feeCanPaidType ==\'3\' " class="glyphicon glyphicon-refresh m-l-xs primary text-info" title="重试付款" ng-click="grid.appScope.retryEvent(row.entity.feeStatusStr,row.entity.id)" ></a>'
                                            + '</div>',
                                enableColumnMenu: false, enableSorting: false, cellTooltip: true, headerTooltip: true,
                            },
			],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged(this.$scope,(skipSize,pageSize)=>{
                    this.paginationChanged(skipSize,pageSize,this.$state);
                });
                // gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
                gridApi.core.notifyDataChange("options");
                gridApi.core.on.sortChanged(this.$scope, this.sortChange);
                gridApi.selection.on.rowSelectionChanged(this.$scope, this.selectChange);
            }   
        };
        
        this.$scope.getBankName = this.commonService.debounce(this.getBankName,500);
        this.loadReckonerIdListDropDown();
        this.loadValueDropDown();
        //权限
        this.canSettleReturnAuthority();
        this.canSettlePayAuthority();
        this.query();
        //点击事件
        this.$scope.selectedAll = ()=>{this.selectedAll(this.$scope.gridOptions.data)};
        this.$scope.backEvent = this.backEvent;
        this.$scope.settlePay = this.settlePay;
        this.$scope.payEvent = this.payEvent;
        this.$scope.clearSelectAll = this.clearSelectAll;
        this.$scope.settleDetailBtn = this.settleDetail;
        this.$scope.deleteSelectedPayData = (id)=>{this.deleteSelectedPayData(id,this.$scope.gridOptions.data)};
        this.$scope.retryEvent = this.retryEvent;
        this.$scope.searchType = this.searchType;

         /*datetimepicker*/
        $('#opendataTime').click(function () {
            $('#dataTime').datetimepicker('show');
        });
        $('#opendataTimeEnd').click(function () {
            $('#dataTimeEnd').datetimepicker('show');
        });
        
    }

    loadData(queryTerms:IFeeSettlePayManageQueryTerms,skip:number,count:number):void{
        if(queryTerms.feeStatus === "" || !queryTerms.feeStatus){ this.feeStatusList = "6,7,8,9,10,11"; }else{
            this.feeStatusList = queryTerms.feeStatus;
        }
        if(queryTerms.feeStatus === "10"){ this.feeStatusList = "10,11" };
        //11.1 新增查询条件 费用金额 queryTerms.feeTotal
        this.feeService.getFeeSettleBillList(this.orderBy.toString(),this.asc,queryTerms.feeSettleBillCode,"",queryTerms.carrierName,queryTerms.paymentMethod,queryTerms.startTime,queryTerms.endTime,queryTerms.feeTotal,queryTerms.reckonerId,queryTerms.contractNumber,this.feeStatusList,"","",true,skip,count).then(result=>{
            // this.$scope.gridOptions.totalItems = result.data.total;

            this.$scope.gridOptions.data = result.data.data;
            this.resumeSelectedItem(this.$scope.gridOptions.data);
            this.$scope.heightA = ((this.$scope.gridOptions.data.length * 39) + 95);
            if(skip==0){ this.$scope.gridOptions.paginationCurrentPage = 1; };
            this.$scope.querying = false;
        })
        
    }

    getListCount():void{
        /**获取列表总数 */
        if(this.$scope.queryTerms.feeStatus === "" || !this.$scope.queryTerms.feeStatus){ this.feeStatusList = "6,7,8,9,10,11"; }else{
            this.feeStatusList = this.$scope.queryTerms.feeStatus;
        }
        if(this.$scope.queryTerms.feeStatus === "10"){ this.feeStatusList = "10,11" };
        //11.1 新增查询条件 费用金额 queryTerms.feeTotal
        this.feeService.getFeesettlebillcount(this.$scope.queryTerms.feeSettleBillCode, "", this.$scope.queryTerms.carrierName, this.$scope.queryTerms.paymentMethod,this.$scope.queryTerms.startTime, this.$scope.queryTerms.endTime, 
        this.queryTerms.feeTotal, this.queryTerms.reckonerId, this.queryTerms.contractNumber, this.feeStatusList, "", "").then((res)=>{
              this.$scope.gridOptions.totalItems=res.data.extData;
          })
    }

    localHistory():void{
        super.localHistory(this.$state)
    }
    getHistory():void{
        super.getHistory(this.$state,this.$location)
    }

    /**
     * 排序事件触发
     */
    sortChange=(grid: uiGrid.IGridInstanceOf<FeeSettleBillListItemResponse>, sortColumns: Array<uiGrid.IGridColumnOf<FeeSettleBillListItemResponse>>)=> {
        if (sortColumns.length == 0) {
           this.reload();
        } else {
            let sortItem = sortColumns[0];
            switch (sortItem.name) {
                case "billCode": {
                    this.orderBy = 1;
                } break;
                case "carrier": {
                    this.orderBy = 2;
                } break;
                case "feeCount": {
                    this.orderBy = 3;
                } break;
                case "paymentMethod": {
                    this.orderBy = 4;
                } break;
                case "totalMoney": {
                    this.orderBy = 5;
                } break;
                case "feeStatus": {
                    this.orderBy = 6;
                } break;
                case "reckonerName": {
                    this.orderBy = 7;
                } break;
                case "settleTime": {
                    this.orderBy = 8;
                } break;
                case "payTime":{
                    this.orderBy = 9;
                }break;
            }
            this.asc = sortItem.sort.direction == "asc";
            this.reload();
        }
    }

    /**
     * 选择事件
     */
    selectChange=(row:uiGrid.IGridRowOf<FeeSettleBillListItemResponse>)=>{
        if(this.lockSelect){return;};
        if(row.isSelected){
            this.$scope.selectedFeePayListInfo.push({
                id:row.entity.id,
                feeStatus:row.entity.feeStatus,
                billCode:row.entity.billCode
            })
        }else{
            this.$scope.selectedFeePayListInfo.forEach((item,index)=>{
                if(row.entity.id === item.id){
                    this.$scope.selectedFeePayListInfo.splice(index,1);
                }
            });
        }
    }

    /**
     * 删除选中项
     */
    deleteSelectedPayData=(id:string,data:string | FeeSettleBillListItemResponse[])=>{
        this.$scope.selectedFeePayListInfo.forEach((item,index)=>{
            if(id === item.id){
                this.$scope.selectedFeePayListInfo.splice(index,1);
                if(this.isPayListResponse(data)){
                   data.forEach((items,indexs)=>{
                        if(item.id === items.id){
                            if(this.isPayListResponse(data)){
                                this.gridApi.selection.unSelectRow(data[indexs]);
                            }
                        }
                    });
                }
            }
        });
    }

    //断言
    isPayListResponse(response: string | FeeSettleBillListItemResponse[]): response is FeeSettleBillListItemResponse[] {
        return (<FeeSettleBillListItemResponse[]>response).forEach !== undefined;
    }

    /**
     * 全选
     */
    selectedAll=(data:string | FeeSettleBillListItemResponse[])=>{
        if(this.isPayListResponse(data)){
            data.forEach((item,index)=>{
                if(item.feeStatus === "已审核"){
                    if(this.isPayListResponse(data)){
                        this.gridApi.selection.selectRow(data[index]);
                    }
                }
            });
        }
    }

    /**
     * 清除已选
     */
    clearSelectAll=()=>{
        this.gridApi.selection.clearSelectedRows();
        this.$scope.selectedFeePayListInfo.length = 0;
    }


    /**
     * 翻页后选中
     */
    resumeSelectedItem(data:string | FeeSettleBillListItemResponse[]):void{
        if(this.$scope.selectedFeePayListInfo.length <1){return};
        if(this.isPayListResponse(data)){
            data.forEach((item,index)=>{
                this.$scope.selectedFeePayListInfo.forEach((itemS,indexS)=>{
                    if(item.id === itemS.id){
                        this.$timeout(()=>{
                            if(this.isPayListResponse(data)){
                                this.lockSelect = true;
                                this.gridApi.selection.selectRow(data[index]);
                                this.lockSelect = false;
                            }
                        });
                    }
                });
            })
        }
    }

    /**
     * 结算人员下拉
     */
    loadReckonerIdListDropDown():void{
        this.employeeService.getbytype("6",  0, -1).then(result => {
            this.$scope.reckonerIdListDropDown = result.data.data;
        });
    }
 
    //付款按钮权限
    canSettlePayAuthority=()=>{
        var self = this;
		this.authorizationService.auth("24E0A026891BC3909962E29F2964E01B").then(function (res) {
			self.$scope.canSettlePayBtn = res.data.extData;
		});
    };

    canSettleReturnAuthority=()=>{
        var self = this;
		this.authorizationService.auth("24E0A026891BC390AF9C32F2E15606C758DCA74489E47BD8").then(function (res) {
			self.$scope.canSettleReturnBtn = res.data.extData;
		});
    };


    /**
     * 退回
     */
    backEvent=()=>{
        var sFList = this.$scope.selectedFeePayListInfo;
        if(sFList.length > 1){ this.$ngBootbox.alert("结算单只能单笔退回"); return;}else
        if(sFList.length < 1){ this.$ngBootbox.alert("请选择结算单"); return;}else{
            this.$ngBootbox.confirm("确定退回结算单吗?").then(()=>{
                this.feeService.getFeeSettleBillDetail(sFList[0].id).then(res=>{
                    if(res.data.feeStatus === "6" || res.data.feeStatus === "9"){
                        this.feeService.payerReturn(sFList[0].id).then(res=>{
                            sFList.length = 0;
                            this.$scope.gridOptions.paginationCurrentPage = 1;
                            this.reload();
                        })
                    }else{ this.$ngBootbox.alert("退回的结算单必须为已审核或付款失败状态"); }
                })
            })
        }
    }

    /**
     * 导出
     */
    exportFunc=()=>{
        if(this.queryTerms.feeStatus === "" || !this.queryTerms.feeStatus){ this.feeStatusList = "6,7,8,9,10,11"; }else{
            this.feeStatusList = this.queryTerms.feeStatus;
        }
        if(this.queryTerms.feeStatus === "10"){ this.feeStatusList = "10,11" };

        if(this.$scope.gridOptions.totalItems>30000){
            this.$ngBootbox.alert('导出数据不可超过3万条');
            return;
        }else{
            //11.1 新增查询条件 费用金额 queryTerms.feeTotal
            this.exportService.feesettlebillexport(this.orderBy,this.asc,this.queryTerms.feeSettleBillCode,"",this.queryTerms.carrierName, this.queryTerms.paymentMethod,this.queryTerms.startTime,this.queryTerms.endTime,
            this.queryTerms.feeTotal,this.queryTerms.reckonerId,this.queryTerms.contractNumber,this.feeStatusList,"","")
        }

    }

    /**
     * 付款
     */
    payEvent = (id:string) => {
        if(!this.payBtn){return}else{this.payBtn = false};
        this.feeService.getFeeSettleBillDetail(id).then(res=>{
            this.payBtn = true;
            this.$ngBootbox.confirm("确定向银行卡号为" + res.data.bankCode + ",持卡人为" + res.data.holder + ",支付金额为" + res.data.totalMoney + "元吗?").then(()=>{
                this.intervalPay();
                this.feeService.payment(id).then(res=>{
                    this.$loading.finish('feeLoad');
                    this.reload(this.paginationOptions.currentPage);
                    this.$scope.gridOptions.paginationCurrentPage = this.paginationOptions.currentPage;
                },error=>{
                   this.reload(this.paginationOptions.currentPage);
                   this.$scope.gridOptions.paginationCurrentPage = this.paginationOptions.currentPage;
                   this.payBtn = true; 
                });
            },()=>{ this.payBtn = true; });
        })
        this.$timeout(()=>{
            this.$scope.selectedFeePayListInfo = [];
            this.gridApi.selection.clearSelectedRows();
        });
    }

    /**
     * 查询状态
     */
    searchType = (id:string) => {
        this.feeService.queryPayment(id).then(res=>{
            this.reload(this.paginationOptions.currentPage);
            this.$scope.gridOptions.paginationCurrentPage = this.paginationOptions.currentPage;
        });
        this.$timeout(()=>{
            this.$scope.selectedFeePayListInfo = [];
            this.gridApi.selection.clearSelectedRows();
        });
    }

    /**
     * 重试付款按钮 
     */
    retryEvent = (feeStatusStr:string,id:string)=>{
        var id = id;
        this.$scope.openBankDis = true;
        if(feeStatusStr === "11"){
            $("#bankInfo").modal("show");
            this.feeService.getFeeSettleBillDetail(id).then(res=>{
                this.$scope.bankCode = res.data.bankCode;
                this.$scope.bankName = res.data.bankName;
                this.$scope.holder = res.data.holder;
            });
            this.$scope.paySave = ()=>{
               this.paySave(id)
            }
        }else{
            this.paySave(id);
        }
        this.$timeout(()=>{
            this.$scope.selectedFeePayListInfo = [];
            this.gridApi.selection.clearSelectedRows();
        })
    }


    /**
     * 倒计时
     */
    intervalPay=()=>{
        this.$loading.start("feeLoad");
        var time = 3;
        var self = this;
        var timer = this.$interval(()=>{
            time--;
            if (time < 1) {
                this.$interval.cancel(timer);
                this.$loading.finish('feeLoad');
                this.reload(this.paginationOptions.currentPage);
                this.$scope.gridOptions.paginationCurrentPage = this.paginationOptions.currentPage;
            };
        }, 1000);
    }

    /**
     * 获取银行卡名称
     */
    getBankName=()=>{
        var bankCode_value = $("#feeSettlePayCtrl_bankCode").val();
        if (bankCode_value == "" || !bankCode_value) {return;}
        if (bankCode_value.length > 15) {
            this.bankService.getBankName(bankCode_value).then((res)=>{
                if (!res.data) { this.$scope.bankName = ""; this.$scope.openBankDis = false; }else{
                    this.$scope.bankName= res.data;
                    this.$scope.openBankDis = true;
                }
            }, (rej)=>{ this.$scope.openBankDis = false; this.$scope.bankName = ""; return });
        }
    };

    /**
     * 重试付款保存
     */
    paySave=(id:string)=>{
        this.intervalPay();
        this.feeService.paymentRetry(id, this.$scope.holder, this.$scope.bankCode, this.$scope.bankName).then(res=>{
            this.$loading.finish('feeLoad');
            $("#bankInfo").modal("hide");
            this.reload();
        },ref=>{this.$loading.finish('feeLoad'); this.reload();$("#bankInfo").modal("hide");});
    }

    /**
     * 结算单付款
     */
    settlePay=()=>{
        var sFList = this.$scope.selectedFeePayListInfo;
        if(sFList.length < 1){ this.$ngBootbox.alert("请选择需付款的结算单"); return;}
        if(!this.$scope.selectedFeePayListInfo.every(this.isStatusPass)){
            this.$ngBootbox.alert("请选择已审核状态的结算单");
            return;
        }

        this.$ngBootbox.confirm("确定付款吗?").then(()=>{
            let settleId = [];
            sFList.forEach((item,index)=>{ settleId.push(item.id); });
            this.feeService.paid(settleId.join(",")).then(res=>{
                this.$scope.selectedFeePayListInfo.length = 0;
                this.reload();
            }); 
        });


    }

    //结算单付款判断费用状态ev
    isStatusPass(data:selectFeePayList):boolean{
        return !(data.feeStatus !="已审核" && data.feeStatus != "付款失败")
    }


    /**
     * 枚举下拉
     */
    loadValueDropDown():void{
        let  FeeStatusList = this.valueService.getFeeStatusList().data;
        FeeStatusList.splice(0,5);
        this.$scope.feeStatusListDropDown = FeeStatusList;
        this.$scope.paymentMethodDropDown = this.valueService.getPaymentMethodList().data;
    }

    /**
     * 跳转详情页
     */
    settleDetail=(id:string)=>{
         this.$state.go("app.fee.fee_settle_detail", { settleId: id, name: 'settlepay' })
    }
}
angular.module("tms").controller("feeSettlePayManageController",["$scope","feeService","$ngBootbox","$state","routeService","valueService","$loading","bankService","$interval","employeeService","authorizationService","$timeout","$location","exportService","commonService",feeSettlePayManageController])